//
//  ProductDetailViewController.m
//  iShop
//
//  Created by svp on 17/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "HobbiesViewController.h"
#import "CommentsViewController.h"
#import "PurchaseViewController.h"
#import "ProductInfoViewController.h"
#import "UIImageEx.h"
#import "BaseProductImage.h"
#import "BaseProduct.h"
#import "Utils.h"
#import "PromotionViewController.h"
#import "CoreDataUtils.h"
#import "ConstansDefine.h"

@implementation ProductDetailViewController

@synthesize purchaseButton = _purchaseButton;
@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;
@synthesize infoView = _infoView;
@synthesize shop = _shop;
@synthesize product = _product;
@synthesize toolbar = _toolbar;
@synthesize refNumber = _refNumber;
@synthesize btnPromo = _btnPromo;
@synthesize hobbiesButton = _hobbiesButton;
@synthesize functionButton = _functionButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		_isHideToolbar = NO;
    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		_hobbiesButton.enabled = NO;
	}
	else {
		_hobbiesButton.enabled= YES;
	}
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	self.title = [NSString stringWithFormat:@"%@ VND",_product.ProductUnitPrice];
	self.navigationItem.rightBarButtonItem = _purchaseButton;
	if (_isHideToolbar) {
		NSMutableArray     *items = [[_toolbar.items mutableCopy] autorelease];
		[items removeAllObjects];
		_toolbar.items = items;
		
	}
	
	_refNumber.text = _product.ProductRefCode;
	
	NSArray *productImage = [CoreDataUtils getBaseProductImages:_product.BaseProduct];
	_productimagecount = productImage.count;
	//450826
	//NSArray *arr = [ NSArray arrayWithObjects:@"450826a.jpg", @"450826b.jpg", @"450826c.jpg", @"450826d.jpg", @"450826e.jpg", @"450826f.jpg", @"450826g.jpg", @"450826h.jpg",nil];
	if (_productimagecount > 0) {
		for (int i = 0; i < _productimagecount; i++) {
			CGRect frame;
			frame.origin.x = self.scrollView.frame.size.width * i;
			frame.origin.y = 0;
			frame.size = self.scrollView.frame.size;
			BaseProductImage *baseImage = [productImage objectAtIndex:i];
			//UIImage *img = [[Utils getImageOf:@"product" withName:baseImage.BaseProdImage] scaleToSize:frame.size];
			//UIImage *img = [Utils getImageOf:@"product" withName:[arr objectAtIndex:i]];// scaleToSize:frame.size];
			UIImage *img = [Utils getImageOf:@"product" withName:baseImage.BaseProdImage];
			UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
			imgView.contentMode = UIViewContentModeScaleAspectFit;
			imgView.frame = frame;
			[self.scrollView addSubview:imgView];
			[imgView release];
		}
		_pageControl.numberOfPages = _productimagecount;
		_scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * _productimagecount, self.scrollView.frame.size.height);
	}
	else {
		_pageControl.numberOfPages = 0;
		_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width, _scrollView.frame.size.height);
	}

	
	[self.view bringSubviewToFront:_infoView];
	
	//header
	//[_btnPromo removeFromSuperview];
	
	UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 170, 44)];
	header.backgroundColor = [UIColor clearColor];
	UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 170, 22)];
	price.backgroundColor = [UIColor clearColor];
	price.textAlignment = UITextAlignmentCenter;
	price.adjustsFontSizeToFitWidth = YES;
	price.minimumFontSize = 8;
	price.text = [NSString stringWithFormat:@"Price: %@ VND",_product.ProductUnitPrice];
	[header addSubview:price];
	if ([_product.ProductPromoPrice doubleValue] > 0) {
		UILabel *promoPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 22, 170, 22)];	
		promoPrice.backgroundColor = [UIColor clearColor];
		promoPrice.textAlignment = UITextAlignmentCenter;
		promoPrice.text = [NSString stringWithFormat:@"Promo: %@ VND",_product.ProductPromoPrice];	
		promoPrice.adjustsFontSizeToFitWidth = YES;
		promoPrice.minimumFontSize = 8;
		[header addSubview:promoPrice];
	}
	else {
		_btnPromo.hidden = YES; 
	}

	
	self.navigationItem.titleView = header;
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		_purchaseButton.enabled = NO;
		_functionButton.title = @"Comments";
	}
	else {
		_purchaseButton.enabled = YES;
		_functionButton.title = @"More";
	}

}


- (void)dealloc {
	NSLog(@"ProductDetailViewController  dealloc");
	[_purchaseButton release];
    [super dealloc];
}

-(IBAction) homePress:(id) sender
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}

-(IBAction) openHobbies:(id) sender
{
	NSLog(@"openHobbies");
	HobbiesViewController *custom = [[HobbiesViewController alloc] initWithNibName:@"HobbiesViewController" bundle: nil];
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:custom];
	[self.navigationController presentModalViewController:nav animated:YES];
	[custom release];
	[nav release];
}

-(IBAction) purchasePress:(id) sender
{
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"INFO" message:@"You have to login." delegate:nil cancelButtonTitle:@"Dimiss" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	NSLog(@"openHobbies");
	PurchaseViewController *custom = [[PurchaseViewController alloc] initWithNibName:@"PurchaseViewController" bundle: nil];
	
	custom.shop = _shop;
	custom.product = _product;
	[custom prepareData];
	[self.navigationController presentModalViewController:custom animated:YES];
	[custom release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == actionSheet.cancelButtonIndex) {
		return;
	}
	else if (buttonIndex == actionSheet.destructiveButtonIndex) {
		CommentsViewController *custom = [[CommentsViewController alloc] initWithNibName:@"CommentsViewController" bundle: nil];
		custom.baseProduct = _product.BaseProduct;
		[self.navigationController presentModalViewController:custom animated:YES];
		[custom release];

		
	} else {
		if ([CoreDataUtils checkExistWishlistProduct:_product.BaseProduct]) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notice" message:@"Already in Wishlist" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
			[alert show];
			[alert release];
		}		
		else {
			WishlistRequest *req = [[WishlistRequest alloc] init];
			req.delegate = self;
			NSMutableDictionary *infomation = [[[NSMutableDictionary alloc] init] autorelease];
			[infomation setObject:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
			[infomation setObject:_product.BaseProduct.BaseProductID forKey:@"BaseProductID"];
			[infomation setObject:@"ADD" forKey:@"Action"];
			[req makeRequest:infomation];
		}

	}
}

-(void) processRequestResult:(BOOL)result
{
	if (result) {
		[CoreDataUtils addWishList:_product.BaseProduct.BaseProductID];
	}
}

-(IBAction) openComments:(id) sender
{
	NSLog(@"open CommentsViewController");
	if ([((UIBarButtonItem*)sender).title isEqualToString:@"Comments"]) {
		CommentsViewController *custom = [[CommentsViewController alloc] initWithNibName:@"CommentsViewController" bundle: nil];
		custom.baseProduct = _product.BaseProduct;
		[self.navigationController presentModalViewController:custom animated:YES];
		[custom release];
	}
	else {
		UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:@"Choose Function" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"View Comments" otherButtonTitles:@"Add To WishList",nil];
		[choiceSheet showInView:self.view];
	}	
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
	if (!pageControlBeingUsed) {
		// Switch the indicator when more than 50% of the previous/next page is visible
		CGFloat pageWidth = self.scrollView.frame.size.width;
		int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
		self.pageControl.currentPage = page;
	}
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	pageControlBeingUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	pageControlBeingUsed = NO;
}

- (IBAction)changePage {
	// Update the scroll view to the appropriate page
	CGRect frame;
	frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
	frame.origin.y = 0;
	frame.size = self.scrollView.frame.size;
	[self.scrollView scrollRectToVisible:frame animated:YES];
	
	// Keep track of when scrolls happen in response to the page control
	// value changing. If we don't do this, a noticeable "flashing" occurs
	// as the the scroll delegate will temporarily switch back the page
	// number.
	pageControlBeingUsed = YES;
}

-(IBAction) openInfo:(id) sender
{
	NSLog(@"openHobbies");
	ProductInfoViewController *custom = [[ProductInfoViewController alloc] initWithNibName:@"ProductInfoViewController" bundle: nil];
	custom.shop = _shop;
	custom.product = _product;
	[custom prepareData];
	[self.navigationController presentModalViewController:custom animated:YES];
	[custom release];
}

-(void) setHideToolbar:(BOOL)hide
{
	_isHideToolbar = hide;
}

-(IBAction) openPromotion:(id) sender
{
	NSLog(@"Open Promotion");
	PromotionViewController *custom = [[PromotionViewController alloc] initWithNibName:@"PromotionViewController" bundle: nil];
	custom.promotion = _product.Promotion;
	[self.navigationController presentModalViewController:custom animated:YES];
	[custom release];
}


@end
